/*****************************************************************
**                                                              **
**  Copyright (C) 2004 Amlogic,Inc.                             **
**  All rights reserved                                         **
**        Revision : 1.0                                        **
**                                                              **
*****************************************************************/
#include "includes.h"
#include "aw_windows.h"
#include <chipsupport.h>
#include "app.h"
#include "../user.h"
#include "menu.h"
#include "resource/string_dat.h"
#include "txt_app.h"
#include "img_upgrade.h"
#include "filelistEvent.h"
#include "aw_init_display.h"
#include "aw_TXT_app.h"
#include "aw_sys_app.h"
#include "aw_gui_app.h"
#include "aw_config.h"
#include "ctrlconvert.h"
#include "./win/NetmenuSetupEvent.h"
#include "DebugEvent.h"

extern INT32U*writeadd;
extern INT32U last_hotkey ;
#if  HOTKEYENABLE
extern char hotkey_flag ;
#endif

static char device_removed=0;
static unsigned load_txtapp_data[2];
static char play_type = TXT_PLAY_TXT ;

char txt_read_finish = TRUE;

#ifdef ENABLE_WATCHDOG
AVTimer_t sys_restart_time=0;
static void SysTimerFunc(void *arg)
{
     AWGUISendNMMessage(MEDIA_GUI,NM_SYS_RESTART_FINISH,(INT32U)0);
}
#endif
#if (defined BOOT_LOADER)
typedef enum
{
	UPGRADE_INIT = 0,
	UPGRADE_USE_FIXED_MEM,
	UPGRADE_READING,
	UPGRADE_CHECK_OK,
	UPGRADE_ERASING,
	UPGRADING,
	UPGRADE_FINISHED,
	
	
	UPGRADE_ERROR,
	OPEN_FILE_ERROR,
	CRCERROR,
	CHECKSUMERROR,
	MEMORY_MALLOC_ERROR,
	MEMORY_NOT_ENOUGH,
	VERIFY_BUF_ERROR,
	GENERIC_ERROR,
	CHECK_PLATFORM_ERROR,
	
	UPGRADE_WRITING_LOADER,
	UPGRADE_WRITING_BIN,
	UPGRADE_V2_PASS,
	UPGRADE_V2_ERROR_LOADER,
	UPGRADE_V2_ERROR_BIN
}upgrade_process_table;
#endif


static INT8U TxtPlayCmdResponse(AWMSG *pMsg, PCMDSET cmd_set)
{
    INT8U iRet = BREAK_EXECUTE_COMMAND ;
   char **lines ;
    int i = 0 ;
    PHWND hwnd = AWFindWinCtrlByName(DebugConsole) ;

    switch(pMsg->msg_type){
        case MSG_COMMAND_SUCCESS:
            lines = (char **) (pMsg->msg_value) ;
           if(lines && (AWIsVisibleWinControl(hwnd))){
                AWDebugClr();
				
				
                for(i=0 ; i<TXT_DISPLAY_HIGH_IN_LINE ; i++ ) 
               {
                 AWClearRectTxt(hwnd->draw_info[i].draw_pos_x, hwnd->draw_info[i].draw_pos_y,
				 	hwnd->draw_info[i].draw_width, hwnd->draw_info[i].draw_height);

                    if(*lines) {
                        strcpy(debug_string[i], *lines++);
                    }
                   else {
                       strcpy(debug_string[i], "");
                    }
                    AWPostMessage(hwnd, WM_PAINT_DRAW_INFO_CLEAR, i);
               }
           }
          iRet = GO_ON_EXECUTE_COMMAND ;
            break ;
        case MSG_COMMAND_FAIL:
            break ;
        case MSG_COMMAND_FORBIDEN:
            break ;
        case MSG_COMMAND_NOT_SUPPORT:
        default:
            break ;
    }
    return iRet ;
}

static INT8U TxtImgCmdResponse(AWMSG *pMsg, PCMDSET cmd_set)
{
    return GO_ON_EXECUTE_COMMAND ;
}
extern char upgrade_high_light;

void AWTXTQuitProcess(AWMSG *pMsg)
{
	txt_read_finish = TRUE;
    if(device_removed){
        device_removed=0;
        return;
    }
    
    if(play_type == TXT_PLAY_TXT){
        AWShowFileList(1);        
    }
	if(play_type == TXT_PLAY_IMG){
		PHWND hwnd = AWFindWinCtrlByName(WinFileListUpgrade);
		if(hwnd){
			hwnd->draw_info[4].draw_data = (INT32U)ICON_YES_LOSE;
			hwnd->draw_info[5].draw_data = (INT32U)ICON_NO_FOCUS;
			upgrade_high_light = 1;		
			AWPostMessage(hwnd, WM_PAINT_DRAW_INFO, 4) ;
		    AWPostMessage(hwnd, WM_PAINT_DRAW_INFO, 5) ;
		    AWPostMessage(hwnd, WM_PAINT_FINISH, 0) ;
		}
	}
	//AWHideWinControl(AWFindWinCtrlByName("WinFileListUpgrade"));
	//AWShowWinControl(AWFindWinCtrlByName("WinFileInfoBKG"),0); 
	//AWSetFocus(AWFindWinCtrlByName("FileListPreview"));     
}

void AWTXTQuitProcess2(AWMSG *pMsg)
{
#if HOTKEYENABLE
	if(hotkey_flag)
	{
		//ReloadLogo();
		APPHotKeyProcess(&last_hotkey);
		hotkey_flag = 0 ;
		return ;
	}
#endif
}

int AWTXTCheckHead(AML_ImageHeader *head)
{
    if(head->platformID == 455555) {
	
		return 0 ;
		
    }
    return 1 ;
    
}
// flag 0 or 1 ,0: play txt file  1:image upgrade
// line_interrupt the txt show line number (if image upgrade mode,1 close interrupt  0 don't close interrupt)
// wide the txt show char numbers of one line 
int PlayTxtFile(char *file_name, INT8U flag, INT16U line_interrupt, INT16U wide)
{
    txt_read_finish = FALSE;

    PCMDSET pCmd, pCmd1 ;
    INT8U my_app_id ;

    AWGetAppID(MEDIA_TXT, &my_app_id) ; 
    if (AWGetAppStatus(my_app_id) != APP_RUNNING) {
        AWAppRunning(my_app_id) ;
    }
    
    if(flag == TXT_PLAY_IMG) {
        pCmd1 = AWCommandSetMalloc();
        pCmd1->command_num = 1;
        pCmd1->curr_executed_cmd_num = 0;
        pCmd1->commands[0] = TXT_CMD_SET_IMG_CHECK_FUN;
        pCmd1->commands_para[0] = (unsigned)AWTXTCheckHead;
        pCmd1->ExecuteResultProcess = TxtImgCmdResponse;
        pCmd1->cmd_timeout_value[0] = 5; 
        pCmd1->app_id = my_app_id ;
        AWAddCommandSet(pCmd1);
    }
    pCmd = AWCommandSetMalloc();
    pCmd->command_num = 1;
    pCmd->curr_executed_cmd_num = 0;
    pCmd->commands[0] = CM_PLAY;
    pCmd->commands_para[0] = (unsigned)load_txtapp_data;
    load_txtapp_data[0] = (unsigned)file_name;
    if(flag == TXT_PLAY_IMG) {
        load_txtapp_data[1] = (1 << TXT_APP_IMAGE_TYPE_BIT) | (line_interrupt) ;
        play_type = TXT_PLAY_IMG ;
        pCmd->ExecuteResultProcess = TxtImgCmdResponse;
    }
    else {
        play_type = TXT_PLAY_TXT ;
        pCmd->ExecuteResultProcess = TxtPlayCmdResponse;
        load_txtapp_data[1] = (line_interrupt << TXT_APP_TXT_LINE_BIT) | (wide << TXT_APP_TXT_WIDE_BIT) ;
    }
    pCmd->cmd_timeout_value[0] = 5; 
    pCmd->app_id = my_app_id ;
    AWAddCommandSet(pCmd);

    return 1;
}

void AWTXTKeyDo(INT32S key, INT32S Param)
{
    INT8U my_app_id ;
    INT16U pCmds;
    INT32U pCmdsParam ;
    INT8U pCmdTimeOut ;
    PAPPTASKARG pTXTAppArg;

    AWGetAppID(MEDIA_TXT, &my_app_id) ; 
    switch(key){
        case UOP_RESUME:
        case UOP_STOP:
            if(txt_read_finish == TRUE)
            {
                pTXTAppArg = AWGetAppArg(MEDIA_TXT) ;   
                AWAppSendMessage(pTXTAppArg->app_id, pTXTAppArg->app_msg_q,  pTXTAppArg->app_event_handle,
                                MSG_QUIT, 0, 0) ;
                AWTXTQuitProcess(0) ;
			}
            break ;
        case UOP_FAST_FORWARD:
        case UOP_DOWN:
            pCmds = CM_FORWARD_SLOW ;
            pCmdTimeOut = 2 ;
            AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, TxtPlayCmdResponse) ;
            break ;
        case UOP_FAST_BACKWARD:
        case UOP_UP:
            pCmds = CM_BACKWARD_SLOW ;
            pCmdTimeOut = 2 ;
            AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, TxtPlayCmdResponse) ;
            break ;
        case UOP_NEXT_CHAP:
        case UOP_RIGHT:
            pCmds = CM_FORWARD_SCAN ;
            pCmdTimeOut = 2 ;
            AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, TxtPlayCmdResponse) ;
            break ;         
        case UOP_PREVIOUS_CHAP:
        case UOP_LEFT:
            pCmds = CM_BACKWARD_SCAN ;
            pCmdTimeOut = 2 ;
            AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, TxtPlayCmdResponse) ;
            break ;     
        case UOP_TIME_PLAY:
            if(Param != -1) {
                pCmds = CM_TIME_SEARCH ;
                pCmdsParam = Param ;
                pCmdTimeOut = 2 ;
                AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, TxtPlayCmdResponse) ;
            }
            break ;     
    }
    return ;
}


void AWTXTKeyProcess(AWMSG *pMsg)
{
    if(play_type == TXT_PLAY_TXT) {
        AWTXTKeyDo(pMsg->msg_value, -1) ;
    }
}

void AWTXTNotificationProcess(AWMSG *pMsg)
{	
	char *p_str,str_get[20];
    INT16U StrLen;
    static int percent = 101 ;
	static int temp_percent = 0;
	static int pre_max_percent = 0;
	static int cur_percent = 0;
	#if (defined BOOT_LOADER)
    upgrade_process_table process = (upgrade_process_table)pMsg->msg_value;
	#else	
    upgrade_process_t process = (upgrade_process_t)pMsg->msg_value;
	#endif

    if(pMsg->msg_id == NM_PLAY_STATUS_CHANGED) {
        switch(process) {
			
            case UPGRADE_READING :
                percent = 0 ;
                strcpy(UpgradeInfo, "upgrade reading") ;
                FLUpdateUpgradeControl(0) ;
                break;
            case UPGRADE_USE_FIXED_MEM :
                //strcpy(UpgradeInfo, "use fixed memory") ;
                //FLUpdateUpgradeControl(0) ; 
                p_str = (char *)AWGetResource(UPGRADE_READ_STR, &StrLen);
				strncpy(str_get, p_str, StrLen);
				str_get[StrLen] = 0 ; 
			
                sprintf(UpgradeInfo,"%s %d%%",str_get,0) ;
	            FLUpdateUpgradeControl(4) ;
                break;
            case UPGRADE_CHECK_OK :
                //strcpy(UpgradeInfo, "right img file") ;
                //FLUpdateUpgradeControl(0) ;
                break;
            case UPGRADE_ERASING :
                percent = 0 ; 
				//strcpy(UpgradeInfo, "upgrade erasing") ;
	            //FLUpdateUpgradeControl(3);
	            p_str = (char *)AWGetResource(UPGRADE_ERASE_STR, &StrLen);
				strncpy(str_get, p_str, StrLen);
				str_get[StrLen] = 0 ; 
				
				strcpy(UpgradeInfo,str_get) ;				
                FLUpdateUpgradeControl(2);
                break;
            case UPGRADING :
                strcpy(UpgradeInfo, "upgrade burning") ;
                //FLUpdateUpgradeControl(0) ;
                break;
            case UPGRADE_FINISHED :
                ClearParaInit();
                strcpy(UpgradeInfo, " Finish") ;
                FLUpdateUpgradeControl(2) ;
			chip_power_on(1);
/*                     #ifdef ENABLE_WATCHDOG
                     *writeadd=0x55aaaa55;
			if(!sys_restart_time)
			  sys_restart_time = AVTimerCreateFlag(6000, SysTimerFunc , NULL, AVTIMER_FLAG_PERIODIC);
			else
			  AVTimerRestart(sys_restart_time);
			#endif
*/			
                break;
            case UPGRADE_ERROR :
                strcpy(UpgradeInfo, "not support flash") ;
                FLUpdateUpgradeControl(0) ;
                break;
            case OPEN_FILE_ERROR :
                strcpy(UpgradeInfo, "open file error") ;
                FLUpdateUpgradeControl(0) ;
                break;
            case CRCERROR :
                strcpy(UpgradeInfo, "img crc error") ;
                FLUpdateUpgradeControl(0) ;
                break;
            case CHECKSUMERROR :
                strcpy(UpgradeInfo, "check sum error") ;
                FLUpdateUpgradeControl(0) ;
                break;
            case MEMORY_MALLOC_ERROR :
                //strcpy(UpgradeInfo, "memory malloc error") ;
                //FLUpdateUpgradeControl(0) ;
                p_str = (char *)AWGetResource(UPGRADE_READ_STR, &StrLen);
				strncpy(str_get, p_str, StrLen);
				str_get[StrLen] = 0 ; 
			
                sprintf(UpgradeInfo,"%s %d%%",str_get,0) ;
	            FLUpdateUpgradeControl(4) ;
                break;
            case VERIFY_BUF_ERROR :
                strcpy(UpgradeInfo, "verify buffer error") ;
                FLUpdateUpgradeControl(0) ;
                break;
            case CHECK_PLATFORM_ERROR :
                strcpy(UpgradeInfo, "wrong upgrade file") ;
                FLUpdateUpgradeControl(0) ;
				break;
        }
        return ;
    }
    if((pMsg->msg_id == NM_PLAY_TIME_CHANGED) && (percent != pMsg->msg_value)) {
        if(play_type == TXT_PLAY_IMG) {
            percent = pMsg->msg_value ;
			
			/*calc the right percent to show*/		
			if(percent < temp_percent)								
				pre_max_percent = cur_percent;
			temp_percent = percent;
			cur_percent = pre_max_percent + percent;
			
            sprintf(UpgradeInfo,"%d%%", cur_percent) ;
			if(percent>5)
				FLUpdateUpgradeControl(1) ;
	     }
        else {
         UpdateDebugPage(pMsg->msg_value, 0) ;
        }
    }
	static char once_flag = 0;
    if((pMsg->msg_id == NM_PLAY_TRACK_CHANGED) && (percent != pMsg->msg_value)) {
        if(play_type == TXT_PLAY_IMG) {
			
			p_str = (char *)AWGetResource(UPGRADE_READ_STR, &StrLen);
			strncpy(str_get, p_str, StrLen);
			str_get[StrLen] = 0 ; 
				
            percent = pMsg->msg_value ;
            sprintf(UpgradeInfo,"%s %d%%", str_get,percent) ;
            FLUpdateUpgradeControl(4) ;
        }
        else {
            txt_read_finish = TRUE; 
            UpdateDebugPage(pMsg->msg_value, 1) ;
        }
    }
}

void AWTXTBroadCastProcess(AWMSG* pMsg)
{
    INT8U my_app_id ;
    INT16U pCmds;
    INT32U pCmdsParam ;
    INT8U pCmdTimeOut ;
    CHARSTR* temp;
    if(pMsg->msg_id==BM_DEVICE_PRE_UNMOUNT){
        temp=((DEV_MOUNT_INFO *)(pMsg->msg_value))->mount_point_name;
        if (strncmp((char*)load_txtapp_data[0], temp, strlen(temp)) == 0) {
            device_removed=1;
            AWGetAppID(MEDIA_TXT, &my_app_id) ; 
            pCmdTimeOut = 0 ; /* need not response */
            pCmds = CM_STOP ;
            pCmdsParam = 0 ;
            AWAddCmdSet(1, &pCmds, &pCmdsParam, &pCmdTimeOut, my_app_id, TxtPlayCmdResponse) ;
//			unmount_is_otherusb = 0;
        }
//		else unmount_is_otherusb = 1;
    } 
//    AWSysBroadCastProcess(pMsg);       
}    

void AWTXTMsgProcess(AWMSG *pMsg)
{
    switch(pMsg->msg_type){
        case MSG_INPUT_EVENT:
            if(pMsg->msg_id == WM_KEYDOWN)
                AWTXTKeyProcess(pMsg) ;
            break ;
        case MSG_NOTIFICATION:
            AWTXTNotificationProcess(pMsg) ;
            break ;
        case MSG_QUIT:
            AWTXTQuitProcess2(pMsg);
            break;
        case MSG_BROADCAST:
            AWTXTBroadCastProcess(pMsg);
            break;    
        default:
            break ;
    }
    return ;
}
// this function use for stop all share with the flash ,for upgrade function.

void AWTXTStopAll()
{
    set_flash_clocks_cycle(22);
#ifdef ENABLE_WATCHDOG
disable_hw_watchdog();
#endif

#ifdef ENABLE_USBDRV
    USB_stop_all();
#endif    
}
#if 0

unsigned upgrade_buf_define[][2]=
{
    {1, 0x200000},  //total buf number and total buf size
    {0x0c00000, 0x0Dfffff}, // first buf start address and size
};

unsigned char *AWTXTGetFixedMem()
{

    return (unsigned char *)(&(upgrade_buf_define[0][0])); 
}
#endif
